//
//  MyViewController.m
//  coachmanage
//
//  Created by 众拳科技 on 2018/3/6.
//  Copyright © 2018年 众拳科技. All rights reserved.
//

#import "MyViewController.h"
#import "MyInfoViewController.h"
#import "CZQMySetViewController.h"
#import "VenueVipViewController.h"
#import "CZQResumeIfoViewController.h"
#import "SaleReportViewController.h"
#import "CommonClassReportViewController.h"
#import "CZQMyCourseViewController.h"
#import "CZQStudentExeViewController.h"
#import "CZQMyOderVC.h"
#import "FeedBackViewController.h"
#import "CZQMyhomePageVC.h"
#import "CZQMsterPageVC.h"
@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource>

{
    
    //是否登录
    BOOL _isLogin;
    
}

/**
 //数据源
 */
@property(nonatomic,strong)NSMutableArray *dataArr;

/**
 tableView
 */
@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)UserAccount *userAccount;

@end

@implementation MyViewController

-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:YES];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //解决tablView向下偏移偏移
    
    if (@available(iOS 11.0, *)) {
        
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = NO;
        
    }
    
    
    
    self.view.backgroundColor = BackGroundColor;
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    _isLogin = [userDefault boolForKey:@"isLogin"];
    
    NSString *mater = [userDefault objectForKey:@"MasterType"];
    
    
    
    
    
    [self requestData];
    
    [self loadData];
    
    self.userAccount = [UserAccount account];
    
//    self.userAccount.MasterType = @"1";
    
    
    
    
    
    [NotificationCenter addObserver:self selector:@selector(loadData) name:@"ReloadUser" object:nil];
    
    if ([mater integerValue] == 0) {
        //师傅
        
        if (_isLogin == NO) {
            self.navigationController.navigationBar.hidden = YES;
            FreeUseView *freeUseView = [[FreeUseView alloc] initWithFrame:self.view.frame];
            [freeUseView.freeUseBtn addTarget:self action:@selector(goToLogin)];
            [freeUseView.loginBtn addTarget:self action:@selector(goToLogin)];
            [self.view addSubview:freeUseView];



            [freeUseView mas_remakeConstraints:^(MASConstraintMaker *make) {

                make.edges.mas_equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
            }];
        }
        
    }
    
    // Do any additional setup after loading the view.
}


/**
 数据处理
 */
-(void)requestData
{
    if ([self.userAccount.MasterType integerValue] == 0) {
        //教练
        self.dataArr = [NSMutableArray arrayWithArray:@[@"我的主页",@"我的课件",@"我的订单",@"学员案列",@"意见反馈"]];
    }else
    {
        //师傅
        self.dataArr = [NSMutableArray arrayWithArray:@[@"我的主页",@"我的徒弟",@"我的粉丝",@"设置",@"意见反馈"]];
    }
    
    [self.tableView reloadData];
    
}


-(void)loadData{
    
    NSUserDefaults *userDetault = [NSUserDefaults standardUserDefaults];
    
    NSString *userId = [userDetault objectForKey:@"UserID"];
    
    NSString *url =[NSString stringWithFormat:@"%@/%@",Get_Users,userId];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [HTTPTool GET:url parameters:params
     
          success:^(id responseObject){
              
              NSLog(@"%@",responseObject);
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSDictionary *dict = [responseObject objectForKey:@"users"];
                  
                  
                  if (dict) {
                      UserAccount *userAccount = [UserAccount mj_objectWithKeyValues:dict];
                      
                      self.userAccount = userAccount;
                      
//                      [UserAccount saveAccount:userAccount];
                      
                      [self requestData];
                      
                  }
                  
                  
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark -- 懒加载

-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        
//        CGRectMake(0, CZQ_NavigationBarHeight + CZQ_StatusBarHeight, kScreenWidth, kScreenHeight - (CZQ_NavigationBarHeight + CZQ_StatusBarHeight + CZQ_TabbarHeight) )
        
        UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        tableView.delegate=self;
        
        tableView.dataSource=self;
        
        tableView.backgroundColor = CSClearColor;
        
        tableView.estimatedRowHeight = 50;
        
        [self.view addSubview:tableView];
        
        [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {

            make.edges.mas_equalTo(self.view);

        }];
        
        
        
        //        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        //注册
        //                [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        

        [tableView registerNib:[UINib nibWithNibName:@"CZQMyTableViewCell" bundle:nil]  forCellReuseIdentifier:@"CZQMyTableViewCell"];
        
        [tableView registerNib:[UINib nibWithNibName:@"CZQMyFourTableViewCell" bundle:nil]  forCellReuseIdentifier:@"CZQMyFourTableViewCell"];
        
        [tableView registerNib:[UINib nibWithNibName:@"CZQMyTwoTableViewCell" bundle:nil]  forCellReuseIdentifier:@"CZQMyTwoTableViewCell"];
        
        [tableView registerNib:[UINib nibWithNibName:@"CZQMyTirTableViewCell" bundle:nil]  forCellReuseIdentifier:@"CZQMyTirTableViewCell"];
        
        //        [tableView registerNib:[UINib nibWithNibName:@"YDTrainingTableViewCell" bundle:nil]  forCellReuseIdentifier:@"cell"];
        
        _tableView = tableView;
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

//行数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([self.userAccount.MasterType integerValue] == 1) {
        return 2;
    }
    return 3;
}

//列数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if ([self.userAccount.MasterType integerValue] == 1) {
        if (section == 1) {
            
            return self.dataArr.count;
            
        }
    }else
    {if (section == 2) {
        
        return self.dataArr.count;
        
    }}
    
    
    return 1;
}

//cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WS(weakSelf);
    
    if (indexPath.section == 0) {
        
        if (_isLogin) {
            
            //登录状态
            CZQMyTableViewCell *oneCell = [tableView dequeueReusableCellWithIdentifier:@"CZQMyTableViewCell"];
            
            oneCell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [oneCell setBackgroundView:[UIView new]];
            
            if (self.userAccount) {
                
                NSString *urlStr = [NSString stringWithFormat:@"%@%@",self.userAccount.Pic ,mid_image];
                urlStr=[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                
                [oneCell.myIconBtn sd_setImageWithURL:[NSURL URLWithString:urlStr] forState: UIControlStateNormal placeholderImage:PlaceHold];
                
                
                oneCell.myNameLable.text = self.userAccount.NickName?self.userAccount.NickName:self.userAccount.Name;
                
                oneCell.signatureLable.text = self.userAccount.Memo?self.userAccount.Memo:@"";
                
                oneCell.sexImage.image = [self.userAccount.Sex isEqualToString:@"0"]?[UIImage imageNamed:@"icon_man"]:[UIImage imageNamed:@"icon_women"];
            }
            
            if ([self.userAccount.MasterType integerValue] == 1) {
                
                [oneCell.moreBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.width.mas_equalTo(0);
                }];
                
                [oneCell.myResumeBtn setTitle:@"我的档案"];
            }
            
            
            
            //移除复用
            [oneCell.moreBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
            [oneCell.myResumeBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
            
            //我的简历
            [oneCell.myResumeBtn bk_addEventHandler:^(id sender) {
                
                CZQResumeIfoViewController *resumeVC = [CZQResumeIfoViewController new];
                
                resumeVC.userAccount = self.userAccount;
                
                resumeVC.title = @"我的档案";
                
                [self.navigationController pushViewController:resumeVC animated:YES];
                
                
                
            } forControlEvents:UIControlEventTouchUpInside];
            
            //设置
            [oneCell.moreBtn bk_addEventHandler:^(id sender) {
                
                CZQMySetViewController *setVC = [CZQMySetViewController new];
                
                [self.navigationController pushViewController:setVC animated:YES];
                
                
                
            } forControlEvents:UIControlEventTouchUpInside];
            
            return oneCell;
            
        }else
        {
            //未登录
            CZQMyFourTableViewCell *fourCell = [tableView dequeueReusableCellWithIdentifier:@"CZQMyFourTableViewCell"];
            
            fourCell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            //登录或注册
            //移除复用
            [fourCell.loginBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];

            [fourCell.loginBtn bk_addEventHandler:^(id sender) {

                
                
                LoginViewController *loginVC = [[LoginViewController alloc] init];
                
                UserNavigationController *naVC = (UserNavigationController *)weakSelf.navigationController;
                
//                naVC.isLoginNav= YES;
                
                [naVC pushViewController:loginVC animated:YES];

//                [weakSelf.tableView reloadData];



            } forControlEvents:UIControlEventTouchUpInside];
            
            return fourCell;
            
        }
        
        
        
    }
    else if (indexPath.section == 1 && [self.userAccount.MasterType integerValue] == 0)
    {
        
        CZQMyTwoTableViewCell *twoCell = [tableView dequeueReusableCellWithIdentifier:@"CZQMyTwoTableViewCell"];
        
        twoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        //会员管理
        [twoCell.memberBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
        
        [twoCell.memberBtn bk_addEventHandler:^(id sender) {
            
            VenueVipViewController *venueVc = [VenueVipViewController new];
            
            venueVc.title = @"会员";
            
            [weakSelf.navigationController pushViewController:venueVc animated:YES];
            
        } forControlEvents:UIControlEventTouchUpInside];
        
        //销售管理
        [twoCell.saleBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
        
        [twoCell.saleBtn bk_addEventHandler:^(id sender) {
            
            SaleReportViewController *saleRe = [SaleReportViewController new];
            
            [weakSelf.navigationController pushViewController:saleRe animated:YES];
            
        } forControlEvents:UIControlEventTouchUpInside];
        
        //课程管理
        [twoCell.courseBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
        
        [twoCell.courseBtn bk_addEventHandler:^(id sender) {
            
            CommonClassReportViewController *courseRecode = [CommonClassReportViewController new];
            
            [weakSelf.navigationController pushViewController:courseRecode animated:YES];
            
        } forControlEvents:UIControlEventTouchUpInside];
        
        
        return twoCell;
        
    }
    
    CZQMyTirTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"CZQMyTirTableViewCell"];
    
    cell.titleLable.text = self.dataArr[indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell  ;
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section != 0) {
        
        return  10;
        
    }
    return 0.00001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    
    return [[UIView alloc]initWithFrame:CGRectZero];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        UIView *view = [UIView new];
        
        view.backgroundColor = CSWhiteColor;
        
        return view;
        
    }
    
    return [[UIView alloc]initWithFrame:CGRectZero];
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当离开某行时，让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
    if (indexPath.section == 2 || (indexPath.section == 1 && [self.userAccount.MasterType integerValue] == 1)) {
        
        if (_isLogin) {
            
            
            if (indexPath.row == 0) {
                
                //师傅
                if ([self.userAccount.MasterType integerValue] == 1) {
                    //我的主页
                     CZQMsterPageVC *home = [CZQMsterPageVC new];
                    
                    
                    [self.navigationController pushViewController:home animated:YES];
                    
                    return;
                }
                
                //我的主页
                CZQMyhomePageVC *home = [CZQMyhomePageVC new];
                
                
                [self.navigationController pushViewController:home animated:YES];
                
            }else if (indexPath.row == 1){
                
                //师傅
                if ([self.userAccount.MasterType integerValue] == 1) {
                    //我的徒弟
                    VenueVipViewController *venueVc = [VenueVipViewController new];
                    
                    venueVc.title = @"我的徒弟";
                    
                    [self.navigationController pushViewController:venueVc animated:YES];
                    
                    return;
                }
                
                
                
                //我的课件
                CZQMyCourseViewController *myCourse = [CZQMyCourseViewController new];
                
                [self.navigationController pushViewController:myCourse animated:YES];
            }
            else if (indexPath.row == 2){
                //师傅
                if ([self.userAccount.MasterType integerValue] == 1) {
                    //我的粉丝
                    VenueVipViewController *venueVc = [VenueVipViewController new];
                    
                    venueVc.title = @"我的粉丝";
                    
                    [self.navigationController pushViewController:venueVc animated:YES];
                    
                    return;
                }
                
                //我的订单
                CZQMyOderVC *oder = [CZQMyOderVC new];
                
                [self.navigationController pushViewController:oder animated:YES];
            }
            else if (indexPath.row == 3){
                
                //师傅
                if ([self.userAccount.MasterType integerValue] == 1) {
                    //我的设置
                    CZQMySetViewController *setVC = [CZQMySetViewController new];
                    
                    [self.navigationController pushViewController:setVC animated:YES];
                    
                    return;
                }
                
                //学员案列
                CZQStudentExeViewController *exe = [CZQStudentExeViewController new];
                
                [self.navigationController pushViewController:exe animated:YES];
            }
            else if (indexPath.row == 4){
                //意见反馈
                FeedBackViewController *feed = [FeedBackViewController new];
                
                [self.navigationController pushViewController:feed animated:YES];
                
            }
            else if (indexPath.row == 5){
                //我的品牌
                FeedBackViewController *feed = [FeedBackViewController new];
                
                [self.navigationController pushViewController:feed animated:YES];
                
            }
            
            
            
        }else
        {
            
            [MBProgressHUD showText:@"请先登录" toview:self.view];
            
            return ;
            
        }
        
    }else if (indexPath.section == 0)
    {
        
        if (_isLogin) {
            
            //个人详情
            MyInfoViewController *infoVc = [MyInfoViewController new];
            
            infoVc.userAccount = self.userAccount;
            
            [self.navigationController pushViewController:infoVc animated:YES];
            
            
        }
        
    }
    
}

#pragma 没有登录 点击使用 去登录页面
-(void)goToLogin{
    
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    
    UserNavigationController *naVC = (UserNavigationController *)self.navigationController;
    
    naVC.isLoginNav= YES;
    
    [naVC pushViewController:loginVC animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:YES];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
